import json
import os

import appium.webdriver
from selenium import webdriver
import logging.handlers

from config import DIR_PATH, HOST


class GetDriver:
    __app_driver = None
    __web_driver = None

    # 获取app driver
    @classmethod
    def get_app_driver(cls):
        if cls.__app_driver is None:
            desired_caps = {
                'platformName': 'Android',  # 被测手机是安卓
                'platformVersion': '12',  # 手机安卓版本
                'deviceName': 'Pixel_4_XL_Edited_API_32:5554',  # 设备名，安卓手机可以随意填写
                'appPackage': 'com.tpshop.malls',  # 启动APP Package名称
                'appActivity': '.SplashActivity',  # 启动Activity名称
                'unicodeKeyboard': True,  # 使用自带输入法，输入中文时填True
                'resetKeyboard': True,  # 执行完程序恢复原来输入法
                'noReset': True,  # 不要重置App
                'newCommandTimeout': 6000,
                'automationName': 'UiAutomator2'
            }
            # 设置driver
            cls.__app_driver = appium.webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps)
        return cls.__app_driver

    # 获取web driver
    @classmethod
    def get_web_driver(cls):
        if cls.__web_driver is None:
            cls.driver = webdriver.Chrome()
            cls.driver.get(HOST)
            cls.driver.maximize_window()
        return cls.driver


# 读取json工具
def read_json(filename, key):
    file_path = DIR_PATH + os.sep + "data" + os.sep + filename
    arrs = []
    with open(file_path, "r", encoding='utf-8') as f:
        for data in json.load(f).get(key):
            arrs.append(tuple(data.values())[1:])
        return arrs

def write_json(value):
    file_path = DIR_PATH + os.sep + "data" + os.sep + "expect.json"
    with open(file_path,"w",encoding="utf-8")as f:
        data = {"expect":[{"desc":"app订单编号","order_no":value}]}
        json.dump(data,f)

# 日志封装
class GetLog:
    __log = None
    @classmethod
    def get_log(cls):
        if cls.__log is None:
            # 获取日志器
            cls.__log = logging.getLogger()
            # 设置入口级别
            cls.__log.setLevel(logging.INFO)
            # 获取处理器
            filename = DIR_PATH + os.sep + "log" + os.sep + "tpshop_auto.log"
            tf = logging.handlers.TimedRotatingFileHandler(filename=filename,when="midnight",interval=1,backupCount=3,encoding='utf-8')
            # 获取格式器
            fmt = "%(asctime)s %(levelname)s [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s"
            fm = logging.Formatter(fmt)
            # 将格式器添加到处理器
            tf.setFormatter(fm)
            # 将处理器添加到日志器
            cls.__log.addHandler(tf)
        return cls.__log

if __name__ == '__main__':
    print(read_json("app_order.json","order"))
    GetLog.get_log().info("测试")